﻿
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using MS.Core.Configuration;
using MS.Core.Model;
using System.Text;
using System.Threading.Tasks;

namespace ReportDesignerServer
{
    /// <summary>
    /// 
    /// </summary>
    public static class JWTSetup
    {
        public static void AddJwtSetup(this IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
            {
                var jwtSettings = AppSettingHelper.GetModel<JwtSettings>("JwtSettings");
                //var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
                byte[] keyBytes = Encoding.UTF8.GetBytes(jwtSettings.SecrentKey);
                var secKey = new SymmetricSecurityKey(keyBytes);
                opt.TokenValidationParameters = new()
                {
                    ValidateIssuer = true, //验证颁发者
                    ValidIssuer = jwtSettings.Issuer,
                    ValidateAudience = true,  // 验证使用者
                    ValidAudience = jwtSettings.Audience,
                    ValidateLifetime = true, //是否验证Token有效期，使用当前时间与Token的Claims中的NotBefore和Expires对比
                    ValidateIssuerSigningKey = true, //验证秘钥
                    IssuerSigningKey = secKey,
                    RequireExpirationTime = true,//要求Token的Claims中必须包含Expires
                    ClockSkew = TimeSpan.Zero, //允许服务器时间偏移量300秒，即我们配置的过期时间加上这个允许偏移的时间值，才是真正过期的时间(过期时间 + 偏移值)你也可以设置为0，ClockSkew = TimeSpan.Zero
                };

            });
        }
    }
}
